package com.hspedu.spring.annotation1;

import org.springframework.beans.BeansException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author： charlie
 * @Date： 2025/11/5 21:25
 * @Describe：
 */

public class CSpringApplicationContext {
    private Class configClass;
    private ConcurrentHashMap<String, Object> ioc =
            new ConcurrentHashMap();

    public Object getBean(String name) throws BeansException {
        return ioc.get(name);
    }


    public CSpringApplicationContext(Class configClass) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        this.configClass = configClass;
        System.out.println("this is config class: " + configClass);
        ComponentScan componentScan = (ComponentScan) this.configClass.getDeclaredAnnotation(ComponentScan.class);
        System.out.println("this is componentScan: " + componentScan.value());
        String path = componentScan.value();
        ClassLoader classLoader =
                CSpringApplicationContext.class.getClassLoader();

        path = path.replace('.', '/');
        URL resource = classLoader.getResource(path);
        System.out.println("this is resource: " + resource);

        File file = new File(resource.getFile());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                System.out.println("============");
                String absolutePath = f.getAbsolutePath();
                if (absolutePath.endsWith(".class")) {
                 String className = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.indexOf(".class"));
                 String classFullName=path.replace("/",".")+"."+className;

                    Class<?> aClass = classLoader.loadClass(classFullName);
                    if(aClass.isAnnotationPresent(Component.class)) {
                        Class<?> aClass1 = Class.forName(classFullName);
                        Object instance = aClass1.newInstance();
                        ioc.put(StringUtils.uncapitalize(className), instance);
                    }




                }
            }
        }


    }
}


